package org.apache.ocean.main.search.tag;

import java.io.IOException;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.ocean.main.search.tag.TagIndex.TermData;
import org.apache.ocean.main.util.SortedLongList;

public class TagIndexFile {
	public static final String FILE_NAME = "tags.idx";
	private Directory directory;
	
	public TagIndexFile(Directory directory) {
		this.directory = directory;
	}
	
	public TagIndex load() throws IOException {
		IndexInput indexInput = directory.openInput(FILE_NAME);
		int version = indexInput.readInt();
		long transactionId = indexInput.readLong();
		int mapSize = indexInput.readVInt();
		NavigableMap<Term, TermData> map = new TreeMap<Term, TermData>();
		for (int x=0; x < mapSize; x++) {
			String field = indexInput.readString();
			String text = indexInput.readString();
			Term term = new Term(field, text);
			int docsLength = indexInput.readVInt();
			int[] docArray = new int[docsLength];
			for (int doc=0; doc < docsLength; doc++) {
				docArray[doc] = indexInput.readVInt();
			}
			SortedLongList sortedIntList = new SortedLongList(docArray);
			TermData termData = new TermData(term, sortedIntList);
			map.put(term, termData);
		}
		return new TagIndex(directory, map);
	}
	
	void write(TagIndex tagIndex) throws IOException {
		SortedMap<Term, TermData> map = tagIndex.getMap();
		IndexOutput indexOutput = directory.createOutput(FILE_NAME);
		indexOutput.writeInt(1); // version
		indexOutput.writeVInt(map.size());
		for (TermData termData : map.values()) {
			Term term = termData.getTerm();
			indexOutput.writeString(term.field());
			indexOutput.writeString(term.text());
			int[] docs = termData.getDocs();
			indexOutput.writeVInt(docs.length);
			for (int doc : docs) {
				indexOutput.writeVInt(doc);
			}
		}
		indexOutput.close();
	}
}
